<template>
  <view class="problem-container">
    <!-- 顶部导航 -->
    <NavigationBar title="问题与建议" />

    <!-- 顶部背景装饰 -->
    <view class="top-decoration">
      <image
        src="https://picsum.photos/seed/beauty-feedback/800/300"
        mode="aspectFill"
        class="w-full h-60 rounded-b-3xl opacity-90"
      ></image>
      <view class="top-overlay">
        <view class="px-6 pb-12">
          <text class="text-3xl font-bold text-white">问题与建议</text>
          <view class="mt-2 text-white opacity-90">
            我们重视每一位客户的体验和反馈
          </view>
        </view>
      </view>
    </view>

    <view class="content-wrapper">
      <!-- 表单卡片 -->
      <view class="form-card">
        <view class="form-title">提交反馈</view>

        <!-- 问题类型选择 -->
        <view class="mb-9">
          <view class="text-gray-700 text-[28rpx] font-medium mb-[18rpx]"
            >反馈类型<text class="text-rose-500 ml-1">*</text></view
          >
          <view class="grid grid-cols-2 gap-3 mt-2">
            <view
              class="h-[90rpx] flex items-center justify-center bg-gray-50 rounded-xl border border-gray-100 transition-all duration-200 active:scale-95"
              :class="{
                'bg-orange-50 border-amber-600 shadow-sm':
                  formData.type === 'service',
              }"
              @tap="selectType('service')"
            >
              <image
                src="../../static/public/icon-service.png"
                class="w-[40rpx] h-[40rpx] mr-3"
                mode="aspectFit"
              ></image>
              <text
                class="text-[28rpx] font-medium text-gray-600"
                :class="{ 'text-amber-700': formData.type === 'service' }"
                >服务体验</text
              >
            </view>

            <view
              class="h-[90rpx] flex items-center justify-center bg-gray-50 rounded-xl border border-gray-100 transition-all duration-200 active:scale-95"
              :class="{
                'bg-orange-50 border-amber-600 shadow-sm':
                  formData.type === 'product',
              }"
              @tap="selectType('product')"
            >
              <image
                src="../../static/public/icon-product.png"
                class="w-[40rpx] h-[40rpx] mr-3"
                mode="aspectFit"
              ></image>
              <text
                class="text-[28rpx] font-medium text-gray-600"
                :class="{ 'text-amber-700': formData.type === 'product' }"
                >产品问题</text
              >
            </view>

            <view
              class="h-[90rpx] flex items-center justify-center bg-gray-50 rounded-xl border border-gray-100 transition-all duration-200 active:scale-95"
              :class="{
                'bg-orange-50 border-amber-600 shadow-sm':
                  formData.type === 'complaint',
              }"
              @tap="selectType('complaint')"
            >
              <image
                src="../../static/public/icon-complaint.png"
                class="w-[40rpx] h-[40rpx] mr-3"
                mode="aspectFit"
              ></image>
              <text
                class="text-[28rpx] font-medium text-gray-600"
                :class="{ 'text-amber-700': formData.type === 'complaint' }"
                >商家投诉</text
              >
            </view>

            <view
              class="h-[90rpx] flex items-center justify-center bg-gray-50 rounded-xl border border-gray-100 transition-all duration-200 active:scale-95"
              :class="{
                'bg-orange-50 border-amber-600 shadow-sm':
                  formData.type === 'suggestion',
              }"
              @tap="selectType('suggestion')"
            >
              <image
                src="../../static/public/icon-suggestion.png"
                class="w-[40rpx] h-[40rpx] mr-3"
                mode="aspectFit"
              ></image>
              <text
                class="text-[28rpx] font-medium text-gray-600"
                :class="{ 'text-amber-700': formData.type === 'suggestion' }"
                >功能建议</text
              >
            </view>
          </view>
        </view>

        <!-- 内容输入区 -->
        <view class="mb-9">
          <view class="text-gray-700 text-[28rpx] font-medium mb-[18rpx]"
            >问题描述<text class="text-rose-500 ml-1">*</text></view
          >
          <textarea
            class="w-full h-[240rpx] bg-gray-50 rounded-xl p-5 text-[28rpx] text-gray-700 border border-gray-100"
            v-model="formData.content"
            placeholder="请详细描述您遇到的问题或建议，以便我们更好地解决和改进（10-200字）"
            maxlength="200"
            :adjust-position="true"
          ></textarea>
          <view class="text-right text-[24rpx] text-gray-400 mt-2"
            >{{ formData.content.length }}/200</view
          >
        </view>

        <!-- 图片上传 -->
        <!-- <view class="mb-9">
          <view class="text-gray-700 text-[28rpx] font-medium mb-[18rpx]"
            >上传图片（可选，最多3张）</view
          >
          <view class="flex flex-wrap gap-4">
            <view
              v-for="(item, index) in formData.images"
              :key="index"
              class="relative w-[160rpx] h-[160rpx]"
            >
              <image
                :src="item"
                mode="aspectFill"
                class="w-full h-full rounded-lg"
              ></image>
              <text
                class="absolute -top-[10rpx] -right-[10rpx] w-[40rpx] h-[40rpx] bg-black bg-opacity-50 text-white rounded-full flex items-center justify-center text-[24rpx] iconfont icon-close"
                @tap="deleteImage(index)"
              ></text>
            </view>

            <view
              v-if="formData.images.length < 3"
              class="w-[160rpx] h-[160rpx] bg-gray-50 border border-dashed border-gray-300 rounded-lg flex items-center justify-center"
              @tap="chooseImage"
            >
              <text class="iconfont icon-add text-[48rpx] text-gray-400"></text>
            </view>
          </view>
        </view> -->

        <!-- 联系方式 -->
        <view class="mb-9">
          <view class="text-gray-700 text-[28rpx] font-medium mb-[18rpx]"
            >联系方式（可选）</view
          >
          <input
            class="w-full h-[80rpx] bg-gray-50 rounded-xl px-5 text-[28rpx] text-gray-700 border border-gray-100"
            v-model="formData.contact"
            placeholder="手机号或微信号，方便我们与您联系"
            type="text"
          />
        </view>

        <!-- 提交按钮 -->
        <button
          class="w-full h-[88rpx] flex items-center justify-center text-[30rpx] font-medium text-white rounded-xl shadow-md transition-all duration-200 active:scale-98"
          :class="
            isFormValid
              ? 'bg-gradient-to-r from-amber-600 to-amber-500 shadow-amber-600/20'
              : 'bg-gray-200 text-gray-400'
          "
          :disabled="!isFormValid"
          @tap="submitFeedback"
        >
          提交反馈
        </button>
      </view>

      <!-- 底部安全区域 -->
      <view class="safe-area-bottom"></view>
    </view>
  </view>
</template>

<script setup lang="ts">
import NavigationBar from "@/components/navigationBar/index.vue";
import { ref, computed, onMounted } from "vue";
import { submitQuestionSuggestion, getUserQuestionSuggestions } from "@/api";
import type { QuestionSuggestionAddRequest } from "@/api";

// 反馈类型
const feedbackTypes = ref([
  {
    label: "服务体验",
    value: "service",
    icon: "/static/public/service.png",
  },
  {
    label: "产品问题",
    value: "product",
    icon: "/static/public/product.png",
  },
  {
    label: "商家投诉",
    value: "complaint",
    icon: "/static/public/complaint.png",
  },
  {
    label: "功能建议",
    value: "suggestion",
    icon: "/static/public/suggestion.png",
  },
]);

// 表单数据
const formData = ref({
  type: "service", // 默认选择服务体验
  content: "",
  images: [] as string[],
  contact: "",
});

// 用户信息
const userInfo = ref<any>(null);

// 历史记录
const historyList = ref<any[]>([]);
// 以下变量与历史记录相关，暂时注释
/*
const currentPage = ref(1);
const pageSize = ref(10);
const hasMore = ref(false);
*/

// 表单验证
const isFormValid = computed(() => {
  return formData.value.type && formData.value.content.length >= 10;
});

// 选择类型
const selectType = (type: string) => {
  formData.value.type = type;
};

// 选择图片
const chooseImage = () => {
  if (formData.value.images.length >= 3) {
    uni.showToast({ title: "最多上传3张图片", icon: "none" });
    return;
  }

  uni.chooseImage({
    count: 3 - formData.value.images.length,
    sizeType: ["compressed"],
    sourceType: ["album", "camera"],
    success: (res) => {
      // 这里应该有上传图片到服务器的逻辑
      // 上传成功后获取图片URL并添加到images数组
      // 这里简化处理，直接使用本地临时路径
      formData.value.images = [...formData.value.images, ...res.tempFilePaths];
    },
  });
};

// 删除图片
const deleteImage = (index: number) => {
  formData.value.images.splice(index, 1);
};

// 预览图片
const previewImage = (images: string[], current: number) => {
  uni.previewImage({
    urls: images,
    current: images[current],
  });
};

// 提交反馈
const submitFeedback = async () => {
  if (!isFormValid.value) {
    uni.showToast({ title: "请完善表单信息", icon: "none" });
    return;
  }

  // 检查用户登录状态
  if (!userInfo.value || !userInfo.value.id) {
    uni.showModal({
      title: "提示",
      content: "请先登录后再提交反馈",
      confirmText: "去登录",
      cancelText: "取消",
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({ url: "/pages/login/index" });
        }
      },
    });
    return;
  }

  try {
    uni.showLoading({ title: "提交中..." });

    // 准备提交数据
    const submitData: QuestionSuggestionAddRequest = {
      userId: parseInt(userInfo.value.id),
      content: `【${getTypeName(formData.value.type)}】${formData.value.content}${formData.value.contact ? ` 联系方式：${formData.value.contact}` : ""}`,
    };

    // 调用API提交
    const response = await submitQuestionSuggestion(submitData);

    if (response.code === 200) {
      // 重置表单
      formData.value.content = "";
      formData.value.images = [];
      formData.value.contact = "";
      formData.value.type = "service";

      // 成功提示
      uni.hideLoading();
      uni.showToast({
        title: "提交成功，我们会尽快处理您的反馈",
        icon: "none",
      });
    } else {
      throw new Error(response.message || "提交失败");
    }
  } catch (error: any) {
    uni.hideLoading();
    uni.showToast({
      title: error.message || "提交失败，请重试",
      icon: "none",
    });
    console.error("提交反馈失败:", error);
  }
};

// 获取类型名称
const getTypeName = (type: string) => {
  const typeItem = feedbackTypes.value.find((item) => item.value === type);
  return typeItem ? typeItem.label : "未知类型";
};

// 页面加载时获取用户信息
onMounted(() => {
  // 获取存储的用户信息
  try {
    const storedUserInfo = uni.getStorageSync("userInfo");
    if (storedUserInfo) {
      userInfo.value = storedUserInfo;
    }
  } catch (error) {
    console.error("获取用户信息失败:", error);
  }
});
</script>

<style lang="scss" scoped>
.problem-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #faf8f5 0%, #f5f2ee 100%);
  position: relative;

  .iconfont {
    font-family: "iconfont";
  }
}

.top-decoration {
  position: relative;
  height: 340rpx;
  overflow: hidden;

  .top-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(
      to right,
      rgba(175, 108, 49, 0.8),
      rgba(212, 165, 116, 0.7)
    );
    display: flex;
    align-items: center;
  }
}

.content-wrapper {
  margin-top: -120rpx;
  padding: 0 30rpx 80rpx;
  position: relative;
  z-index: 10;
}

.form-card {
  background-color: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20rpx;
  padding: 40rpx;
  box-shadow: 0 8rpx 30rpx rgba(175, 108, 49, 0.1);
  margin-bottom: 40rpx;
  border: 1px solid rgba(175, 108, 49, 0.1);
}

.form-title {
  font-size: 34rpx;
  font-weight: 600;
  color: #111827;
  margin-bottom: 30rpx;
  padding-bottom: 16rpx;
  border-bottom: 1px solid #f3f4f6;
}

.history-card {
  background-color: #ffffff;
  border-radius: 20rpx;
  padding: 40rpx;
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.05);
  margin-bottom: 40rpx;
}

.history-title {
  font-size: 34rpx;
  font-weight: 600;
  color: #111827;
  margin-bottom: 30rpx;
  padding-bottom: 16rpx;
  border-bottom: 1px solid #f3f4f6;
}

.tips-card {
  background-color: #ffffff;
  border-radius: 20rpx;
  padding: 60rpx 40rpx;
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.tips-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.tips-text {
  font-size: 30rpx;
  font-weight: 500;
  color: #374151;
  margin-bottom: 10rpx;
}

.tips-desc {
  font-size: 26rpx;
  color: #6b7280;
}

.safe-area-bottom {
  height: 40rpx;
}

@font-face {
  font-family: "iconfont";
  src: url("data:application/x-font-woff2;charset=utf-8;base64,BASE64_ENCODED_FONT"); /* 此处应替换为实际的字体图标 */
}

/* 以下是字体图标定义，实际开发时应替换为项目中使用的图标 */
.icon-service:before {
  content: "\e634";
}
.icon-product:before {
  content: "\e635";
}
.icon-complaint:before {
  content: "\e636";
}
.icon-suggestion:before {
  content: "\e637";
}
.icon-add:before {
  content: "\e638";
}
.icon-close:before {
  content: "\e639";
}
.icon-phone:before {
  content: "\e640";
}
</style>
